package com.atguigu.srb.core.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.atguigu.srb.core.mapper.DictMapper;
import com.atguigu.srb.core.pojo.data.DictData;
import com.atguigu.srb.core.pojo.entity.Dict;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
//@Component
public class DictExcelDataListener extends AnalysisEventListener<DictData> {
//    List<DictData> data = new ArrayList<>();
    //一个类装配容器中的组件时 必须保证自己的对象也会被容器创建
//    @Resource
    DictMapper dictMapper;

    public DictExcelDataListener(DictMapper dictMapper) {
        this.dictMapper = dictMapper;
    }

    @Override
    public void invoke(DictData dictData, AnalysisContext analysisContext) {
        //1、判断读到的数据 数据库中是否已存在，如果存在 不保存
        Long id = dictData.getId();
        Integer count = dictMapper.selectCount(Wrappers.lambdaQuery(Dict.class)
                .eq(Dict::getId, id));
        if(count>0){
            return;
        }
        //2、如果数据库中不存在，导入到数据库中
        //将dictData对象属性值设置给Dict的对象
        Dict dict = new Dict();
        dict.setId(id);
        dict.setParentId(dictData.getParentId());
        dict.setName(dictData.getTitle());
        dict.setValue(dictData.getValue());
        dict.setDictCode(dictData.getCode());
//        dict.set
        dictMapper.insert(dict);

    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        //批量保存数据到数据库表中
//        //
//        System.out.println("读取到的所有数据："+data);
    }
}
